package myapps.ttclient.activity.ppt;

import myapps.ttclient.activity.DeletePrivateDataActivity;
import myapps.ttclient.activity.MouseControllerActivity;
import myapps.ttclient.activity.ds.DSOpenFileActivity;
import myapps.ttclient.activity.ds.DSSaveFileActivity;
import myapps.ttclient.app.TTClientApplication;
import myapps.ttclient.baseclass_and_interface.TTClientMessage;
import myapps.ttclient.baseclass_and_interface.TTClientMessageReceiver;
import myapps.ttclient.dialog.DSActionsPlusPlusDialog;
import myapps.ttclient.dialog.PPTActionsPlusPlusDialog;
import myapps.ttclient.model.PPTSlideShowModel;
import myapps.ttclient.protocol.message.ScreenSizeRequestMessage;
import myapps.ttclient.protocol.message.ScreenSizeResponseMessage;
import myapps.ttclient.protocol.message.drawingscreen.DSActionMessage;
import myapps.ttclient.protocol.message.drawingscreen.DSClearAllSlides;
import myapps.ttclient.protocol.message.drawingscreen.DSClearCurrentSlide;
import myapps.ttclient.protocol.message.powerpoint.PPTBlackScreenRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTDisableBroadcastingRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTEnableBroadcastingRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTEndRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTGotoSlideRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTHideDrawingScreenRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTNextRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTPrevRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTShowDrawingScreenRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTTCPSlideShowScreenCaptureMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTSlideShowDataResponseMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTStartRequestMessage;
import myapps.ttclient.protocol.message.powerpoint.PPTWhiteScreenRequestMessage;
import myapps.ttclient.udpreceiver.ScreenshotReceiver;
import myapps.ttclient.udpreceiver.ScreenshotReceiver_WithFeedback;
import myapps.ttclient.udpreceiver.ScreenshotReceiver_WithoutFeedback;
import myapps.ttclient.GlobalVariables;
import myapps.ttclient.Helper;
import myapps.ttclient.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.Browser.SearchColumns;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

public class PPTSlideShowScreenActivity extends Activity 
implements TTClientMessageReceiver {

	private static final int START_MENU_ITEM_ID = 1;
	private static final int END_MENU_ITEM_ID = 2;
	private static final int PPT_ACTIONS_MENU_ITEM_ID = 3;	
	private static final int DS_ACTIONS_MENU_ITEM_ID = 4;
	private static final int MODE_MENU_ITEM_ID = 5;
	private static final int ENABLE_BROADCASTING_MENU_ITEM_ID = 6;
	private static final int DISABLE_BROADCASTING_MENU_ITEM_ID = 7;
	private static final int TROUBLESHOOT_MENU_ITEM_ID = 8;

	private static final int ENABLE_RECEIVER_MENU_ITEM_ID = 9;
	private static final int DISABLE_RECEIVER_MENU_ITEM_ID = 10;

	private static final int FIT_SCREEN_MENU_ITEM_ID = 11;
	private static final int FULLSCSREEN_MENU_ITEM_ID = 12;

	private TTClientApplication application;
	private SharedPreferences preferences;

	private PPTSlideShowModel _pptSlideShowModel;

	private ScreenshotReceiver _screenShotReceiver = null;

	private PPTDrawingScreen _drawingScreen;

	private Bitmap _bmpDefaultBackground = null;
	private Bitmap _newBitmapFromTCP = null;

	private Button btnPrev;
	private Button btnNext;

	private ImageView _handle;
	private SlidingDrawer _slidingDrawer;

	private ImageView _ivBackground;

	private int _mode = 3;
	private int _currentModeSelected = 3;

	private Boolean _bEnableTemporateSlideShowClick = false;

	private ImageView _ivDrawingScreen;

	public ImageView getDrawingScreenImageView() {
		return _ivDrawingScreen;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/////////////////////////////////////////////////////////
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		Helper.updateFullscreenStatus(this, true);
		Helper.keepScreenOn(this);

		/////////////////////////////////////////////////////////////
		this.application = (TTClientApplication) this.getApplication();
		this.preferences = this.application.getPreferences();

		/////////////////////////////////////////////////////////////
		setContentView(R.layout.slideshow);

		_handle = (ImageView) findViewById(R.id.handle);
		_slidingDrawer = (SlidingDrawer) findViewById(R.id.slidingDrawer);

		_slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			@Override
			public void onDrawerOpened() {
				_handle.setBackgroundResource(R.drawable.sd_handle_1);

			}
		});

		_slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			@Override
			public void onDrawerClosed() {
				_handle.setBackgroundResource(R.drawable.sd_handle_0);

			}
		});

		_ivBackground = (ImageView) findViewById(R.id.imageview_slideshow);

		btnPrev = (Button)findViewById(R.id.buttonPrev);
		btnPrev.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				PPTSlideShowScreenActivity.this.application.sendMessage(new PPTPrevRequestMessage(GlobalVariables.getTemporaryKey()));
			}
		});

		btnNext = (Button)findViewById(R.id.buttonNext);
		btnNext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				PPTSlideShowScreenActivity.this.application.sendMessage(new PPTNextRequestMessage(GlobalVariables.getTemporaryKey()));
			}
		});

		_bmpDefaultBackground = BitmapFactory.decodeStream(this.application
				.getResources().openRawResource(R.drawable.bg_slideshow));

		_ivDrawingScreen = (ImageView) findViewById(R.id.imgv_drawing_screen);
		_drawingScreen = new PPTDrawingScreen(this);

		_pptSlideShowModel = new PPTSlideShowModel();

		if(GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_ADMIN
				|| GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_KEY_MEMBER
		) {
			btnNext.setVisibility(View.VISIBLE);
			btnPrev.setVisibility(View.VISIBLE);

			_screenShotReceiver = ScreenshotReceiver_WithFeedback.getInstance(this, _ivBackground);

			if(_screenShotReceiver != null) {
				_screenShotReceiver.pause();
			}

		} else if(GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_MEMBER) {
			btnNext.setVisibility(View.INVISIBLE);
			btnPrev.setVisibility(View.INVISIBLE);

			_screenShotReceiver = ScreenshotReceiver_WithoutFeedback.getInstance(this, _ivBackground);

			if(_screenShotReceiver != null) {
				_screenShotReceiver.pause();
			}
		}

		//scale(0, 800, 600);
	}

	private void scale(int type, int sWidth, int sHeight) {
		if(_ivBackground == null || _ivDrawingScreen == null) {
			return;
		}

		DisplayMetrics displaymetrics = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		int width = displaymetrics.widthPixels;

		int newHeight = 100;
		int newWidth = 100;

		if(type == 0) {
			// Fit

			float ss = ((float) sWidth / sHeight);
			float cs = ((float) width / height);

			if(ss > cs)
			{
				newWidth = width;
				newHeight = (int) ((float) width / ss); 

			} else {
				newHeight = height;
				newWidth = (int) ((float) height * ss);

			}

		} else if(type == 1) {
			// Fit
			newHeight = height;
			newWidth = width;

		}   else {
			newHeight = height;
			newWidth = width;

		}

		LayoutParams params = (LayoutParams) _ivBackground.getLayoutParams();
		params.height = newHeight;
		params.width = newWidth;
		_ivBackground.setLayoutParams(params);

		LayoutParams params2 = (LayoutParams) _ivBackground.getLayoutParams();
		params2.height = newHeight;
		params2.width = newWidth;
		_ivDrawingScreen.setLayoutParams(params2);

	}

	public Boolean bDone = false;

	public void sendQuitRequestToServer() {
		if(bDone == false) {
			if(GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_ADMIN
					|| GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_KEY_MEMBER) {
				(new AlertDialog.Builder(PPTSlideShowScreenActivity.this))
				.setTitle("Confirming Dialog")
				.setMessage("Tell the server you quit the slide show screen?")
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						PPTSlideShowScreenActivity.this.application.sendMessage(
								new PPTDisableBroadcastingRequestMessage(
										GlobalVariables.getTemporaryKey()));

						PPTSlideShowScreenActivity.this.application.sendMessage(
								new PPTHideDrawingScreenRequestMessage(
										GlobalVariables.getTemporaryKey()));

						PPTSlideShowScreenActivity.this.application.sendMessage(
								new PPTEndRequestMessage(
										GlobalVariables.getTemporaryKey()));
						
						PPTSlideShowScreenActivity.this.finish();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						PPTSlideShowScreenActivity.this.finish();
						
					}
				}).show();
				
			} else {
				PPTSlideShowScreenActivity.this.finish();
			}
			
			bDone = true;
		} 
		
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	(new AlertDialog.Builder(PPTSlideShowScreenActivity.this))
			.setTitle("Confirming Dialog")
			.setMessage("Are you sure?")
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					PPTSlideShowScreenActivity.this.sendQuitRequestToServer();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			}).show();
	    	
	    	
	        return true;
	    }
	    
	    return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.application.registerMessageReceiver(this);
		this._drawingScreen.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.application.unregisterMessageReceiver(this);
		this._drawingScreen.onPause();
	}

	public void processTouchEvent(int type, double x, double y) {
		this.application.sendMessage(new  DSActionMessage(type, x, y));
	}
	
	private Boolean bTCPChanelAvailable = true;

	@Override
	public void receiveMessage(TTClientMessage message) {

		if (message instanceof PPTTCPSlideShowScreenCaptureMessage) {
			
			if(!(GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_ADMIN
					|| GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_KEY_MEMBER)) {
				return;
			}
			
			if(!bTCPChanelAvailable) {
				return;
			}

			PPTTCPSlideShowScreenCaptureMessage msg = (PPTTCPSlideShowScreenCaptureMessage) message;
			
			byte[] buffer = msg.data;
			
			this._newBitmapFromTCP = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
			
			this.application.postToQueue(new Runnable() {
			
				public void run() {		
				_ivBackground.setImageBitmap(_newBitmapFromTCP);
				}
			});

		} else if (message instanceof PPTSlideShowDataResponseMessage) {
			PPTSlideShowDataResponseMessage temp = (PPTSlideShowDataResponseMessage) message;
			this._pptSlideShowModel.set_SlideData(temp.data);

		} else if (message instanceof ScreenSizeResponseMessage) {
			if(bUpdateScreenSize) {
				ScreenSizeResponseMessage srm = (ScreenSizeResponseMessage) message;

				final int width = srm.width;
				final int height = srm.height;

				this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						scale(0, width, height);

					}
				});

				bUpdateScreenSize = false;
			}

		}
	}

	private Boolean bUpdateScreenSize = false;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if(GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_ADMIN 
				|| GlobalVariables.getCurrentAuthority() == GlobalVariables.AUTHORITY_KEY_MEMBER) {
			menu.add(Menu.NONE, START_MENU_ITEM_ID, Menu.NONE, "Start");
			menu.add(Menu.NONE, END_MENU_ITEM_ID, Menu.NONE, "End");
			menu.add(Menu.NONE, PPT_ACTIONS_MENU_ITEM_ID, Menu.NONE, "PPT Actions ++");
			menu.add(Menu.NONE, DS_ACTIONS_MENU_ITEM_ID, Menu.NONE, "DS Action ++");
			menu.add(Menu.NONE, MODE_MENU_ITEM_ID, Menu.NONE, "Mode");
			menu.add(Menu.NONE, FULLSCSREEN_MENU_ITEM_ID, Menu.NONE, "Fullscreen Mode");
			menu.add(Menu.NONE, FIT_SCREEN_MENU_ITEM_ID, Menu.NONE, "Fit Screen Mode");
			menu.add(Menu.NONE, ENABLE_BROADCASTING_MENU_ITEM_ID, Menu.NONE, "Enable Broadcast Receiver");
			menu.add(Menu.NONE, DISABLE_BROADCASTING_MENU_ITEM_ID, Menu.NONE, "Disable Broadcast Receiver");
			menu.add(Menu.NONE, TROUBLESHOOT_MENU_ITEM_ID, Menu.NONE, "Troubleshoot");
			return true;
		} else {
			menu.add(Menu.NONE, ENABLE_RECEIVER_MENU_ITEM_ID, Menu.NONE, "Enable Screenshot Receiver");
			menu.add(Menu.NONE, DISABLE_RECEIVER_MENU_ITEM_ID, Menu.NONE, "Disable Screenshot Receiver");
			menu.add(Menu.NONE, FULLSCSREEN_MENU_ITEM_ID, Menu.NONE, "Fullscreen Mode");
			menu.add(Menu.NONE, FIT_SCREEN_MENU_ITEM_ID, Menu.NONE, "Fit Screen Mode");
			return true;
		}
	}

	private void enableBroadcastReceiver() {
		this.application.showToast("Enable Broadcast Receiver");
		this._screenShotReceiver.unpause();
	}

	private void disableBroadcastReceiver() {
		this.application.showToast("Disable Broadcast Receiver");
		this._screenShotReceiver.pause();
		this.setBackgroundToDefault();
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId())
		{
		case ENABLE_RECEIVER_MENU_ITEM_ID:
			enableBroadcastReceiver();
			break;

		case DISABLE_RECEIVER_MENU_ITEM_ID:
			disableBroadcastReceiver();
			break;

		case START_MENU_ITEM_ID:
			this.application.showToast("Start");
			this.application.sendMessage(new PPTStartRequestMessage(GlobalVariables.getTemporaryKey()));
			//this.application.sendMessage(new PPTEnableBroadcastingRequestMessage(GlobalVariables.getTemporaryKey()));
			//this._screenShotReceiver.unpause();
			break;

		case END_MENU_ITEM_ID:
			this.application.showToast("End");
			this.application.sendMessage(new PPTEndRequestMessage(GlobalVariables.getTemporaryKey()));
			//this.application.sendMessage(new PPTDisableBroadcastingRequestMessage(GlobalVariables.getTemporaryKey()));
			//this._screenShotReceiver.pause();
			this.setBackgroundToDefault();
			break;

		case PPT_ACTIONS_MENU_ITEM_ID:
			(new PPTActionsPlusPlusDialog(this, this.application)).show();
			break;

		case DS_ACTIONS_MENU_ITEM_ID:
			(new DSActionsPlusPlusDialog(this, this.application)).show();
			break;

		case MODE_MENU_ITEM_ID:
			onModeMenuItemSelected();
			break;

		case FULLSCSREEN_MENU_ITEM_ID:			
			scale(1, 1, 1);
			break;

		case FIT_SCREEN_MENU_ITEM_ID:
			this.bUpdateScreenSize = true;
			this.application.sendMessage(new ScreenSizeRequestMessage());
			break;

		case ENABLE_BROADCASTING_MENU_ITEM_ID:
			this.application.sendMessage(new PPTEnableBroadcastingRequestMessage(GlobalVariables.getTemporaryKey()));
			enableBroadcastReceiver();
			bTCPChanelAvailable = false;
			break;

		case DISABLE_BROADCASTING_MENU_ITEM_ID:
			this.application.sendMessage(new PPTDisableBroadcastingRequestMessage(GlobalVariables.getTemporaryKey()));
			disableBroadcastReceiver();
			bTCPChanelAvailable = true;
			break;

		case TROUBLESHOOT_MENU_ITEM_ID:
			this.application.showToast("Troubleshoot");
			PPTSlideShowScreenActivity.this.startActivity(
					new Intent(this, MouseControllerActivity.class));
			break;
		}

		return true;
	}



	public void onGoToSlide() {
		final CharSequence[] items = _pptSlideShowModel.get_Titles();

		if(items != null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Pick a slide");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					PPTSlideShowScreenActivity.this.application.sendMessage(
							new PPTGotoSlideRequestMessage(
									GlobalVariables.getTemporaryKey(), item));
				}
			});
			AlertDialog alert = builder.create();
			alert.show();

		} else {
			Helper.ShowNoticeDialog(this, 
					"Notice", "Cannot perform this function!");
		}
	}

	public void on_BlackScreen_NormalScreen() {
		this.application.sendMessage(new PPTBlackScreenRequestMessage(
				GlobalVariables.getTemporaryKey()));
	}

	public void on_WhiteScreen_NormalScreen() {
		this.application.sendMessage(new PPTWhiteScreenRequestMessage(
				GlobalVariables.getTemporaryKey()));
	}

	public void on_Enable_Drawing_Screen() {
		this.application.sendMessage(new PPTShowDrawingScreenRequestMessage(
				GlobalVariables.getTemporaryKey()));
	}

	public void on_Disable_Drawing_Screen() {
		this.application.sendMessage(
				new PPTHideDrawingScreenRequestMessage(
						GlobalVariables.getTemporaryKey()));
	}

	public void on_Clear_Current_Slide() {
		this.application.sendMessage(
				new DSClearCurrentSlide());
	}

	public void on_Clear_All_Slides() {
		this.application.sendMessage(
				new DSClearAllSlides());
	}

	public void on_Save() {
		this.startActivity(new Intent(this, DSSaveFileActivity.class));
	}

	public void on_Load() {
		this.startActivity(new Intent(this, DSOpenFileActivity.class));
	}

	private void setBackgroundToDefault() {		
		_ivBackground.setImageBitmap(_bmpDefaultBackground);
	}

	private void onModeMenuItemSelected() {
		final String items[] = {	"No Control",
				"Only Navigating Button",
				"Only Drawing Toolbox",
		"All controls"};

		_currentModeSelected = _mode;

		AlertDialog.Builder adBuilder=new AlertDialog.Builder(PPTSlideShowScreenActivity.this);
		adBuilder.setTitle("Pick Layout Mode");
		adBuilder.setSingleChoiceItems(items, _mode,new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				_currentModeSelected = whichButton;   
			}
		})
		.setPositiveButton("Apply", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				_mode = _currentModeSelected;
				PPTSlideShowScreenActivity.this.changeLayout(_mode);
			}
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

			}
		});

		adBuilder.show();
	}



	private void changeLayout(int mode)	{
		if(mode == 0) {
			if(_drawingScreen != null) {
				_drawingScreen.enableTemporateSlideShowClick();
				_bEnableTemporateSlideShowClick = true;
			}
		} else {
			if(_bEnableTemporateSlideShowClick == true){
				_drawingScreen.restoreSlideShowClickState();
				_bEnableTemporateSlideShowClick = false;
			}
		}

		switch(mode) {
		case 0:
			//No control
			btnPrev.setVisibility(View.GONE);
			btnNext.setVisibility(View.GONE);
			_handle.setVisibility(View.GONE);
			_slidingDrawer.setVisibility(View.GONE);
			break;
		case 1:
			//Only Navigating Button
			btnPrev.setVisibility(View.VISIBLE);
			btnNext.setVisibility(View.VISIBLE);
			_handle.setVisibility(View.GONE);
			_slidingDrawer.setVisibility(View.GONE);
			break;
		case 2:
			//Only Drawing Toolbox
			btnPrev.setVisibility(View.GONE);
			btnNext.setVisibility(View.GONE);
			_handle.setVisibility(View.VISIBLE);
			_slidingDrawer.setVisibility(View.VISIBLE);
			break;
		case 3:
			//All Controls
			btnPrev.setVisibility(View.VISIBLE);
			btnNext.setVisibility(View.VISIBLE);
			_handle.setVisibility(View.VISIBLE);
			_slidingDrawer.setVisibility(View.VISIBLE);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this._drawingScreen.onActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}
}
